import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wanxiang_app/bean/order_list_entity.dart';
import 'package:wanxiang_app/bean/simple_entity.dart';
import 'package:wanxiang_app/pages/home/detail.dart';
import 'package:wanxiang_app/pages/sell/sell.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/myappbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter_popup/flutter_popup.dart';

import '../../widgets/simple_dialog.dart';
class GoodsController extends GetxController{
   EasyRefreshController   easyRefreshController = EasyRefreshController(
    controlFinishRefresh: false,
    controlFinishLoad: true,
  );
  @override
  void onInit() {
    super.onInit();

    _getList();
  }
   int clickTabIndex = 0;
   List<Map> tabs=[{'name':'全部','value':''},{'name':'审核中','value':'0'},
     // {'name':'交易中','value':'12'},
     {'name':'已上架','value':'1'},{'name':'交易中','value':'11'}
     ,{'name':'已成交','value':'15'},{'name':'审核失败','value':'23'}];

  List<OrderListData> list = [];
  void _getList(){
    DioManager.getInstance().post(ServiceUrl.myGoodsList,{
      "user_name":UserUtil.getUSER()?.userName.toString()
    }, (data) async {
      OrderListEntity bannerEntity = OrderListEntity.fromJson(jsonDecode(data));
      list = bannerEntity.data;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
  late BuildContext mContext ;
  void _cancel(channel_id,goods_id){
    showDialog(context: mContext, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          Navigator.pop(context1);
          DioManager.getInstance().post(ServiceUrl.cancelGoods,{
            "channel_id":channel_id.toString(),
            "goods_id":goods_id.toString()
          }, (data) async {
            SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
            ToastUtil.show(bannerEntity.msg);
            _getList();
            update();
          }, (error) {
            ToastUtil.show(error);
          });

        }
      },
        msg: "是否撤销商品审核？撤销后该商品不再展示",
        sureText: "确定",
      );
    });

  }

  void _refresh(channel_id,goods_id){
    DioManager.getInstance().post(ServiceUrl.refreshGoods,{
      "user_name":UserUtil.getUSER()?.userName.toString(),
      "channel_id":channel_id.toString(),
      "goods_id":goods_id.toString()
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      _getList();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _off(channel_id,goods_id){
    DioManager.getInstance().post(ServiceUrl.offGoods,{
      "channel_id":channel_id.toString(),
      "goods_id":goods_id.toString()
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      _getList();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  _getStatus(int status){
    if(status == 0){
      return '审核中';
    }
    if(status == 1){
      return '已上架';
    }
    if(status == 23){
      return '审核失败';
    }
    if(status == 21){
      return '自行下架';
    }
    if(status == 22){
      return '强制下架';
    }
    if(status == 11 || status == 12 || status == 13 ){
      return '交易中';
    }
    return '已成交';
  }

}

class GoodsListPage extends  GetView<GoodsController>  {

  late GoodsController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<GoodsController>(() => GoodsController());
    controller = Get.find();
    context = context1;
    controller.mContext = context1;
    return GetBuilder<GoodsController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '我的商品',hasLeading: true,),
            backgroundColor: Colors.white,
            body: controller.list.isEmpty?Container(): _content());
      },
    );
  }


  Widget _content(){
    return Container(
      child: Column(
        children: [
          Container(
              margin: EdgeInsets.only(left:16.w,right: 16.w ,top: 16.h),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: tabsItems(),
              )
          ),
          _line(),
          controller.list.length==0?_empty():
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height - 8.h - 130.h,
            child: _refresh(),
          )
        ],
      ),
    );
  }

  Widget _refresh(){
    return  controller.list.isEmpty?_empty():
    EasyRefresh(
      clipBehavior: Clip.none,
      header: ClassicHeader(
        dragText: 'Pull to refresh'.tr,
        armedText: 'Release ready'.tr,
        readyText: 'Refreshing...'.tr,
        processingText: 'Refreshing...'.tr,
        processedText: 'Succeeded'.tr,
        noMoreText: 'No more'.tr,
        failedText: 'Failed'.tr,
        messageText: 'Last updated at %T'.tr,
      ),
      footer: ClassicFooter(
        dragText: 'Pull to load'.tr,
        armedText: 'Release ready'.tr,
        readyText: 'Loading...'.tr,
        processingText: 'Loading...'.tr,
        processedText: 'Succeeded'.tr,
        noMoreText: 'No more'.tr,
        failedText: 'Failed'.tr,
        messageText: 'Last updated at %T'.tr,
      ),

      controller:controller.easyRefreshController ,
      onRefresh: () async {
      },
      onLoad: () async {
        controller.easyRefreshController.finishLoad(
            IndicatorResult.noMore );
      },
      child: ListView.separated(
        itemBuilder: (context, index) {
          return _gameItems( controller.list[index]);
        }, separatorBuilder: (BuildContext context, int index) {
        return Container(height: 8.h,color: Color(0xFFF7F8FC),);
      }, itemCount: controller.list.length,
      ),
    );
  }


  Widget _line(){
    return Container(
      width: MediaQuery.of(context).size.width,
      color: Color(0xFFF7F8FC),
      height: 8.h,
    );
  }


  List<Widget> tabsItems(){
    List<Widget> aa = [];
    for(int i =0 ;i<controller.tabs.length;i++){
      aa.add(_tabItem(controller.tabs[i]['name'],i));
    }
    return aa;
  }

  Widget _tabItem(name,index){
    return InkWell(
        onTap: (){
          controller.clickTabIndex = index;
          controller._getList();
          controller.update();
        },
        child: Column(
          children: [
            Text(name,style: TextStyle(color:Color(0xFF333333),fontSize: 14.sp),),
            SizedBox(height: 10.h,),
            index == controller.clickTabIndex?
            Container(
              width: 27.w,
              height: 2.h,
              color: Color(0xFFF43F50),
            ):Container(height: 2.h,)
          ],
        )
    ) ;
  }


  Widget _empty(){
    return Container(
      alignment: Alignment.topCenter,
      margin: EdgeInsets.only(top: 40.h),
      child: Text('暂无信息'),
    );
  }


  Widget _gameItems(OrderListData item){
    return
      InkWell(
          onTap: (){
            Get.to(()=>DetailPage(),arguments: {
              'title':item.title,
              'channel_name':"",
              'goods_id':item.id.toString(),
              'status':item.status.toString(),
              'record_id':item.channelId.toString(),
            },preventDuplicates:false)?.then((value) => controller._getList);
          },
          child: Container(
            color: Colors.white,
            margin: EdgeInsets.only(top: 24.h),
            padding: EdgeInsets.all(10.w),
            child:
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('商品编号：${item.guid.toString()}',style: TextStyle(
                      color: Color(0xFF333333),
                      fontWeight: FontWeight.bold,
                      fontSize: 14.sp
                    ),),
                    InkWell(
                      onTap: (){
                        if(item.status== 23){
                          showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return AlertDialog(
                                title: const Text("失败原因"),
                                content:  Text(item.roleText),
                                actions: [
                                  TextButton(onPressed: () {
                                    Navigator.of(context).pop();
                                  }, child: const Text("确定")),
                                ],
                              );
                            },
                          );
                        }
                      },
                      child: Container(
                          child:  Row(
                            children: [
                              item.status== 23?Image.asset(Constant.IMG_BASE+'wenhao.png',width: 11.w,height: 11.w,):Container(),
                              Text(controller._getStatus(item.status),style: TextStyle(
                                  color: Color(0xFFEF3D4E),
                                  fontSize: 12.sp
                              ),),
                            ],
                          )
                      )
                    )
                  ],
                ),


                Container(
                  margin: EdgeInsets.only(top: 13.h,bottom: 13.h),
                  color: Color(0xFFF3F3F3),
                  height: 1.h,
                ),
                Row(
                  children: [
                    Container(
                        width: 100.w,
                        height: 78.h,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10.r),
                        ),
                        child: Stack(
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(10.r),
                              child: Image.network(  Common.realPicPath(item.imgUrl),fit: BoxFit.fitWidth,width: 100.w,height: 78.h,)
                            ),
                            _officer(),
                          ],
                        )

                    ),
                    SizedBox(width: 14.w,),
                    Container(
                        width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w,
                        child:  Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(item.title,
                              style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,),maxLines: 1,    textAlign: TextAlign.left,
                              overflow: TextOverflow.ellipsis,),
                            SizedBox(height: 10.h,),
                            Text('区服：${item.categoryText}',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
                            SizedBox(height: 6.h,),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                item.isMsg==1?
                                _second():Container(),
                                Row(
                                  children: [
                                    Text('￥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                                    Text(item.sellPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 18.sp),),
                                  ],
                                )
                              ],
                            )
                          ],
                        )
                    )
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 13.h,bottom: 13.h),
                  color: Color(0xFFF3F3F3),
                  height: 1.h,
                ),

                _btns(item),
                SizedBox(height: 11.h,)
              ],
            )
           ,
          )
      )
    ;
  }
  
  Widget _second(){
    return Container(
      width: 55.w,
      height: 24.h,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4.r),
        border: Border.all(width: 1.w,color: Color(0xFFffc6bf))
      ),
      child: Text('可二次',style: TextStyle(
        color: Color(0xFFffc6bf),
        fontSize: 12.sp
      ),),
    );
  }
  
  Widget _btns(OrderListData item){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text( Common.transferDate( item.updateTime),style: TextStyle(
          color: Color(0xFF4d4d4d),
          fontSize: 12.sp
        ),)  ,

        _btnStutas(item),

      ],
    );
  }

  Widget _btnStutas(OrderListData item){
    if(item.status == 0){// 审核中
      return Row(
        children: [
          InkWell(
              onTap: (){
                controller._cancel(item.channelId, item.id);
              },
              child: _btn('撤销审核')
          )
          ,
          SizedBox(width: 10.w,),
          InkWell(
            onTap: (){
              Get.to(()=>SellPage(),arguments: {
                'goods_id':item.id.toString(),
                'status':item.status.toString(),
                'channel_id':item.channelId.toString(),
                'channel_name':'',
                'title':item.categoryText,
              },preventDuplicates:false);
            },
            child:  _btn('修改信息1')
          )
         ,
        ],
      );
    }

    if(item.status == 21|| item.status == 23){// 自行下架
      return Row(
        children: [
          InkWell(
            onTap: (){
              Get.to(()=>SellPage(),arguments: {
                'goods_id':item.id.toString(),
                'status':item.status.toString(),
                'channel_id':item.channelId.toString(),
                'channel_name':'',
                'title':'',
              },preventDuplicates:false);
            },
            child: _btn('修改信息3')
          )
          ,
        ],
      );
    }

    if(item.status == 1){// 上架中
      return Row(
        children: [
          InkWell(
              onTap: (){
                Get.to(()=>SellPage(),arguments: {
                  'goods_id':item.id.toString(),
                  'status':item.status.toString(),
                  'channel_id':item.channelId.toString(),
                  'channel_name':'',
                  'title':'',
                },preventDuplicates:false);
              },
              child: _btn('修改信息2')
          )
          ,
          InkWell(
              onTap: (){
                controller._refresh(item.id.toString(), item.channelId.toString());
              },
              child: _btn('刷新')
          )
          ,
          InkWell(
              onTap: (){
                controller._off(item.channelId.toString(), item.id.toString());
              },
              child: _btn('下架')
          )
          ,
        ],
      );
    }

    return Container();
  }

  
  Widget _btn(name){
    return Container(
      margin: EdgeInsets.only(right:5.w ),
      width: 60.w,
      height: 28.h,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(17.r),
        border: Border.all(width: 1.w,color: Color(0xFF4d4d4d))
      ),
      child: Text(name,style: TextStyle(
        color: const Color(0xFF4d4d4d),
        fontSize: 12.sp
      ),),
    );
  }


  Widget _officer() {
    return Container(
      child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
    );
  }


}